﻿using System;
using System.Data;
using System.Data.Common;

namespace BalloonShop.App_Code
{
    /// <summary>
    /// 包含通用数据访问功能的类，业务逻辑层将会调用它
    /// </summary>
    public class GenericDataAccess
    {
        //静态构造函数
        static GenericDataAccess()
        {
            //
            //TODO:在此添加构造函数逻辑
            //
        }

        //执行一个命令并以DataTable对象形式返回结果
        public static DataTable ExcuteSelectCommand(DbCommand command)
        {
            //将返回的Datatable
            DataTable rTable;
            //执行该命令，确保最后关闭了该链接
            try
            {
                //打开数据链接
                command.Connection.Open();
                //执行该命令，将结果保存到DataTable中
                DbDataReader reader = command.ExecuteReader();
                rTable = new DataTable();
                rTable.Load(reader);
                //关闭reader
                reader.Close();
            }
            catch (Exception ex)
            {
                App_Code.Utilities.LogError(ex);
                throw;
            }
            finally
            {
                //关闭数据库连接
                command.Connection.Close();
            }
            return rTable;
        }

        //创建并准备基于新连接的DbCommand对象
        public static DbCommand CreateCommand()
        {
            //获取数据库供应商名称
            string dataProviderName = BalloonShopConfiguration.DbProviderName;
            //获取数据库连接字串
            string connectionString = BalloonShopConfiguration.DbConnectionString;
            //获取新的数据供应商工厂
            DbProviderFactory factory = DbProviderFactories.GetFactory(dataProviderName);
            //获取特定于某种数据库的connection对象
            DbConnection conn = factory.CreateConnection();
            //设置连接字符串
            conn.ConnectionString = connectionString;
            //创建特定于某数据库的command对象
            DbCommand comm = conn.CreateCommand();
            //为存储过程设置命令类型
            comm.CommandType = CommandType.StoredProcedure;
            //返回初始化后的Command对象
            return comm;
        }
    }
}